﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using YAKEJI.Abp.ChineseChar;
using YAKEJI.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Devices;
using YAPACS.BusinessObjects.Managements.StoreServices;
using YAPACS.Organizations;
using YAPACS.RisServer.Abstractions;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.Register;

public class EmergencyRegist(IRepository<Exam, Guid> examRepository, IRepository<Device, Guid> deviceRepository,
    IRepository<Patient, Guid> patientRepository, ICurrentUserOrganization currentUserOrganization,
    IRepository<Department, Guid> departmentRepository, IExamNumberService examNumberService, IChineseCharProvider chineseCharProvider,
    IExamEventService examEventService, IExamQueueService examQueueService, ICandidate candidate)
    : WorkflowBase, IEmergencyRegist, ITransientDependency
{
    private readonly IRepository<Exam, Guid> _examRepository = examRepository;
    private readonly IRepository<Patient, Guid> _patientRepository = patientRepository;
    private readonly IRepository<Device, Guid> _deviceRepository = deviceRepository;
    private readonly ICurrentUserOrganization _currentUserOrganization = currentUserOrganization;
    private readonly IRepository<Department, Guid> _departmentRepository = departmentRepository;
    private readonly IExamNumberService _examNumberService = examNumberService;
    private readonly IChineseCharProvider _chineseCharProvider = chineseCharProvider;
    private readonly IExamEventService _examEventService = examEventService;
    private readonly IExamQueueService _examQueueService = examQueueService;
    private readonly ICandidate _candidate = candidate;

    protected override async Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        var exam = await _examRepository.NewEntityAsync();
        exam.IsEmergency = true;
        exam.IsGreenChannel = true;
        exam.Patient ??= await _patientRepository.NewEntityAsync();
        exam.Patient.Name = "绿通患者";
        const string key = "Input";
        if (input.ContainsKey(key) && input.GetValueOrDefault(key) is Dictionary<string, object> data)
        {
            //检查设备
            if (data.ContainsKey("examDevice"))
            {
                if (Guid.TryParse(data.GetValueOrDefault("examDevice")?.ToString(), out Guid deviceId))
                {
                    var device = await _deviceRepository.GetAsync(deviceId);
                    exam.ExamDevice = device;
                    exam.DeviceType = device.DeviceType;
                }
                else
                {
                    throw new Exception("设备转换错误");
                }
            }
            else
            {
                throw new Exception("设备类型必选");
            }
            //姓名
            if (data.ContainsKey("name"))
            {
                var name = data.GetValueOrDefault("name") as string;
                exam.Patient.Name = name;
            }
            //性别
            if (data.ContainsKey("sex"))
            {
                if (int.TryParse(data.GetValueOrDefault("sex")?.ToString(), out int sex))
                {
                    exam.Patient.Sex = (PatientSex)sex;
                }
            }
            //姓名拼音
            if (data.ContainsKey("namePinYin"))
            {
                var pinyin = data.GetValueOrDefault("namePinYin") as string;
                if ((!string.IsNullOrWhiteSpace(exam.Patient.Name)) && string.IsNullOrWhiteSpace(pinyin))
                {
                    var result = await _chineseCharProvider.GetPinYinAsync(exam.Patient.Name);
                    exam.Patient.NamePinYin = string.Join("", result);
                }
                else
                {
                    exam.Patient.NamePinYin = pinyin;
                }
            }
            //年龄
            if (data.ContainsKey("ageValue"))
            {
                if (int.TryParse(data.GetValueOrDefault("ageValue")?.ToString(), out int ageValue))
                {
                    exam.AgeValue = ageValue;
                }
            }
            //年龄单位
            if (data.ContainsKey("ageUnit"))
            {
                if (int.TryParse(data.GetValueOrDefault("ageUnit")?.ToString(), out int ageUnit))
                {
                    exam.AgeUnit = (AgeUnit?)ageUnit;
                }
            }
            //联系方式
            if (data.ContainsKey("phoneNumber"))
            {
                var phone = data.GetValueOrDefault("phoneNumber") as string;
                exam.Patient.PhoneNumber = phone;
            }

            // 联系方式2
            if (data.ContainsKey("phoneNumber2"))
            {
                var phone2 = data.GetValueOrDefault("phoneNumber2") as string;
                exam.Patient.PhoneNumber2 = phone2;
            }

            //出生日期
            if (data.ContainsKey("birthDate"))
            {
                if (DateTime.TryParse(data.GetValueOrDefault("birthDate")?.ToString(), out DateTime birthDate))
                {
                    exam.Patient.BirthDate = birthDate;
                }
            }
        }
        var department = await _departmentRepository.GetAsync(_currentUserOrganization.DepartmentId.Value);
        exam.Department = department;
        exam.ExamStatus = ExamStatus.Triage;
        exam.StoreService = exam.Department.GetStoreService();
        //创建队列
        exam.ExamQueuing = await _examQueueService.CreateExamQueuingAsync(exam);
        if (string.IsNullOrWhiteSpace(exam.ExamQueuing.CallNumber))
        {
            await _examNumberService.SetQueueNumberAsync(exam.ExamQueuing);
        }
        await _examNumberService.SetNumberAsync(exam);
        await _examEventService.AddExamEventAsync(exam, "新建绿通患者");
        var workflowOutput = await _candidate.InvokeAsync(new WorkflowInput { { "Exams", new List<Exam> { exam } } });
        if (workflowOutput.Success)
        {
            workflowOutput.Data = exam.Oid;
        }
        return workflowOutput;
    }
}
